package com.example.demo.service.impl;

import com.example.demo.entity.Order;
import com.example.demo.mapper.OrderMapper;
import com.example.demo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Order> findAll() {
        return orderMapper.findAll();
    }

    @Override
    public Order findById(Long id) {
        return orderMapper.findById(id);
    }

    @Override
    public Order createOrder(Order order) {
        try {
            // 生成订单编号
            String orderNo = "WX" + LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + 
                           UUID.randomUUID().toString().substring(0, 4);
            order.setOrderNo(orderNo);
            order.setStatus("PENDING");
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());

            // 保存订单到数据库
            String sql = "INSERT INTO orders (order_no, service_type, material_type, item_count, special_requirements, " +
                        "item_description, pickup_address, pickup_time, pickup_date, contact_name, contact_phone, " +
                        "total_amount, status, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            jdbcTemplate.update(sql,
                order.getOrderNo(),
                order.getServiceType(),
                order.getMaterialType(),
                order.getItemCount(),
                order.getSpecialRequirements(),
                order.getItemDescription(),
                order.getPickupAddress(),
                order.getPickupTime(),
                order.getPickupDate(),
                order.getContactName(),
                order.getContactPhone(),
                order.getTotalAmount(),
                order.getStatus(),
                order.getCreateTime(),
                order.getUpdateTime()
            );

            return order;
        } catch (Exception e) {
            throw new RuntimeException("创建订单失败: " + e.getMessage());
        }
    }
} 